package cn.org.cute.ebocy.pf.platformservices;

import java.util.*;
import com.facebook_graph.restapi.*;
import com.facebook_graph.restapi.json.JsonException;
import com.facebook_graph.restapi.json.JsonObject;
import com.facebook_graph.restapi.types.User;
import cn.org.cute.ebocy.config.Param;
import cn.org.cute.ebocy.util.NormalUtil;
import cn.org.cute.security.domain.*;

/**
 * facebook平台的基本api处理
 * 
 * @author xiaolei hiseanxiao@163.com
 * @since 2011-8-10
 * @version v1.0
 */

public class FacebookPlatformDoingImpl {
	private static final String FACEBOOK_GRAPH_ENDPOINT_URL = "https://graph.facebook.com";
	private static final String FACEBOOK_LEGACY_ENDPOINT_URL = "https://api.facebook.com/method";
	DefaultLegacyFacebookClient restClient;
	private FacebookClient graphFacebookClient;
	private static String fields = "name,gender,locale,picture,email";
	public static Parameter parameter = Parameter.with("fields", fields);
	public static Parameter idparameter = Parameter.with("fields", "id");
	private String accessToken = null;

	/**
	 * 获取一个用户的用户信息 根据指定参数，从facebook的api服务器去获得获得平台上去一个用户的用户信息
	 * 
	 * @return 返回一个平台用户信息
	 *         参考http://wiki.developers.facebook.com/index.php/Users.getInfo
	 *         如果取自己的属性
	 *         ：http://developers.facebook.com/docs/reference/rest/users.
	 *         getStandardinfo
	 */
	public PlatformUser getUsersProfile(HashMap<String, String> paramsMap) {
		PlatformUser userProfile = null;
		String uid = paramsMap.get(Param.ParamName.UID.getName());
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		//System.err.println("getUsersProfile------->"+uid+"="+sessionKey);
		if (NormalUtil.isNull(uid) || NormalUtil.isNull(sessionKey)) {
			return userProfile;
		}

		this.connectToPlatform(sessionKey);// 和平台建立通信

		// 登录超时或者非法进入
		String loginUid = this.users_getLoggedInUser();
		//System.err.println("getUsersProfile--loginUid----->"+loginUid);
		if (!uid.equals(loginUid)) {
			return userProfile;
		}

		User user = this.user_Profile(uid);
		return this.getPlatformUserfromUser(user);
	}

	/**
	 * 获得当前登录用户平台ID
	 * 
	 * @param paramMap
	 * @return
	 */
	public String getLoggedInUser(HashMap<String, String> paramsMap) {
		String uid = "0";
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		if (NormalUtil.isNull(sessionKey)) {
			return uid;
		}
		this.connectToPlatform(sessionKey);// 和平台建立通信

		return this.users_getLoggedInUser();
	}

	/**
	 * 获取多个用户的信息 根据指定参数，从facebook的api服务器去获得获得平台上>=1个用户信息
	 * 
	 * @return 返回一个平台用户信息
	 *         参考:http://wiki.developers.facebook.com/index.php/Users.getInfo
	 */
	public List<PlatformUser> getUsersProfiles(HashMap<String, String> paramsMap) {
		List<PlatformUser> userProfiles = null;
		String uid = paramsMap.get(Param.ParamName.UID.getName());
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		String uids = paramsMap.get(Param.ParamName.UIDS.getName());
		if (NormalUtil.isNull(sessionKey) || NormalUtil.isNull(uids)) {
			return userProfiles;
		}

		List<String> ids = new ArrayList<String>();
		for (String id : uids.split(",")) {
			ids.add(id);
		}

		this.connectToPlatform(sessionKey);// 和平台建立通信
		JsonObject usersObject = this.users_getInfos(ids);
		if (usersObject == null) {
			return userProfiles;
		}

		userProfiles = new ArrayList();
		for (String id : ids) {
			try {
				JsonObject userObject = usersObject.getJsonObject(id);
				PlatformUser platformUser = this.getPlatformUserfromJsonObject(userObject);
				if (platformUser != null && id.equals(platformUser.getPfId())) {
					userProfiles.add(platformUser);
				}
			} catch (JsonException e) {
				// e.printStackTrace();
			}
		}

		return userProfiles;
	}

	/**
	 * 獲取添加應用的好友信息,只能得到ID
	 * 
	 * @param ifHaveProperty
	 *            是否需要獲取好友是屬性，true：會取得好友的name,pic,默認只取好友的ID
	 * @return
	 * @throws Exception
	 *            参考地址：http://developers.facebook.com/docs/reference/rest/friends
	 *             .getAppUsers
	 */
	public List<PlatformUser> getAppFriendsInfo(HashMap<String, String> paramsMap) {
		List<PlatformUser> appFriendsList = null;
		String uid = paramsMap.get(Param.ParamName.UID.getName());
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		String needDetail = paramsMap.get(Param.ParamName.INFOED.getName());

		if (NormalUtil.isNull(sessionKey)) {
			return appFriendsList;
		}

		this.connectToPlatform(sessionKey);// 和平台建立通信
		List<String> appFirendIds = this.user_appFriends();
		if (appFirendIds == null) {
			return appFriendsList;
		}
		if(appFirendIds.size() == 0){
			 return new ArrayList<PlatformUser>();
		}

		if ("1".equals(needDetail)) {
			JsonObject usersObject = this.users_getInfos(appFirendIds);
			appFriendsList = new ArrayList();
			for (String id : appFirendIds) {
				try {
					JsonObject userObject = usersObject.getJsonObject(id);
					PlatformUser platformUser = this.getPlatformUserfromJsonObject(userObject);
					if (platformUser != null && id.equals(platformUser.getPfId())) {
						appFriendsList.add(platformUser);
					}
				} catch (JsonException e) {
					// e.printStackTrace();
				}
			}

		} else {
			  appFriendsList = new ArrayList();
			for (String id : appFirendIds) {
				PlatformUser platformUser = new PlatformUser();
				platformUser.setPfId(id);
				appFriendsList.add(platformUser);
			}
			
		}
		
		return appFriendsList;

	}

	/**
	 * 获取所有的朋友<br>
	 * 
	 * @return<br> 平台uid=platformUser.getPfId();<br>
	 *             用户头像=platformUser.getPfMainurl();<br>
	 *             平台用户姓名=platformUser.getPfName();<br>
	 *             具体的请参考PlatformUser对象<br>
	 * @throws Exception
	 * <br>
	 *             参考地址：http://developers.facebook.com/docs/reference/rest/friends
	 *             .get
	 */
	public List<PlatformUser> getFriendsInfo(HashMap<String, String> paramsMap) {
		List<PlatformUser> friendsList = null;
		String uid = paramsMap.get(Param.ParamName.UID.getName());
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		String needDetail = paramsMap.get(Param.ParamName.INFOED.getName());
		if (NormalUtil.isNull(sessionKey)) {
			return friendsList;
		}
		this.connectToPlatform(sessionKey);// 和平台建立通信

		boolean ifneedDetail = ("1".equals(needDetail)) ? true : false;
		// 探险家突然平台ID不对，做如下处理只取当前登录用户的好友列表
		// List<User> users = this.user_ProfileFriends(pfId, ifneedDetail);
		List<User> users = this.user_ProfileFriends(null, ifneedDetail);
		if (users == null || users.size() == 0) {
			return friendsList;
		}

		friendsList = new ArrayList();
		for (User user : users) {
			PlatformUser platformUser = this.getPlatformUserfromUser(user);
			if (platformUser != null
					&& !NormalUtil.isNull(platformUser.getPfId())) {
				friendsList.add(platformUser);
			}
		}

		return friendsList;
	}

	/**
	 * 获得当前登录用户信息 users.getInfo
	 * 
	 * @return
	 * @throws FacebookException
	 */
	public User user_Profile(String pfId) {
		User user = null;
		if (NormalUtil.isNull(pfId)) {
			user = graphFacebookClient.fetchObject("me", User.class, parameter);
		} else {
			user = graphFacebookClient.fetchObject(pfId, User.class, parameter);
		}
	   //System.err.println("user--------->"+user);
		return user;
	}

	/**
	 * 获得当前登录用户uid
	 * 
	 * @return
	 */
	public String users_getLoggedInUser() {
		String loggedInUser = restClient.execute("users.getLoggedInUser",
				String.class);
		// System.err.println("loggedInUser--------->"+loggedInUser);
		return loggedInUser;
	}

	/**
	 * 获得多个用户信息，必须是自己的好友 { "1355346801": { "name": "Sean Xiao", "gender":
	 * "female", "locale": "zh_CN", "id": "1355346801", "picture":"http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs324.snc4/41427_1355346801_3398_q.jpg"
	 * }, "100001610288893": { "name":"\u0e20\u0e34\u0e18\u0e32\u0e23\u0e32\u0e27\u0e14\u0e35 \u0e40\u0e08\u0e23\u0e34\u0e0d\u0e1e\u0e31\u0e19\u0e18\u0e4c"
	 * , "gender": "female", "locale": "th_TH", "id": "100001610288893",
	 * "picture":"http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs717.ash1/161428_100001610288893_6526179_q.jpg"
	 * } }
	 * 
	 * @return
	 * @throws FacebookException
	 * @throws FacebookJsonMappingException
	 */
	public JsonObject users_getInfos(List<String> ids) {
		JsonObject usersObject = null;
		if (ids != null && ids.size() > 0) {
			usersObject = graphFacebookClient.fetchObjects(ids, parameter);
		}
		return usersObject;
	}

	/**
	 * 获得当前登录用户/或好友 的所有好友信息 ifProperties 是否要获得用户的属性
	 * 
	 * @return
	 */
	public List<User> user_ProfileFriends(String uid, boolean ifProperties) {
		Connection<User> myFriends = null;
		String method = "me/friends";
		if (uid != null && !"".equals(uid)) {
			method = uid + "/friends";
		}
		if (ifProperties) {
			myFriends = graphFacebookClient.fetchConnection(method, User.class,
					parameter);
		} else {
			myFriends = graphFacebookClient.fetchConnection(method, User.class,
					idparameter);
		}
		if (myFriends == null) {
			return null;
		}
		return myFriends.getData();
	}

	/**
	 * 获得当前登录用户的加入应用的好友ID
	 * 
	 * @return
	 */
	public List<String> user_appFriends() {
		List<String> appUserList = restClient.executeForList("friends.getAppUsers", String.class);
		// System.err.println("user_appFriends--------->"+appUserList.toString());
		return appUserList;
	}

	/**
	 * user 对象转化为XnUser 对象
	 * 
	 * @param usersObject
	 * @return
	 */
	public PlatformUser getPlatformUserfromUser(User user) {
		PlatformUser platformUser = null;
		if (user == null) {
			return platformUser;
		}

		platformUser = new PlatformUser();
		platformUser.setPfId(user.getId());
		platformUser.setPfName(user.getName());

		// sex
		String gender = user.getGender();
		if (!NormalUtil.isNull(gender) && (gender.equalsIgnoreCase("male") || gender.indexOf("男") >= 0)) {
			 gender = "1";
		} else {
			gender = "0";
		}
		platformUser.setPfSex(gender);

		// pic
		String picture = user.getPicture();
		if (NormalUtil.isNull(picture)) {
			picture = "http://static.ak.fbcdn.net/pics/d_silhouette.gif";
		}

		platformUser.setPfTinyurl(picture);
		platformUser.setPfHeadurl(picture);
		platformUser.setPfMainurl(picture);

		// birthday
		String birthday = user.getBirthday();
		if (!NormalUtil.isNull(birthday)) {
			platformUser.setPfBirthday(birthday);
		}

		// locale
		String locale = user.getLocale();
		if (!NormalUtil.isNull(locale)) {
			platformUser.setPfCountry(locale);
		}

		// email
		String email = user.getEmail();
		if (!NormalUtil.isNull(email)) {
			platformUser.setPfEmail(email);
		}

		return platformUser;

	}

	/**
	 * JsonObject 对象转化为XnUser 对象
	 * 
	 * @param usersObject
	 * @return
	 */
	public PlatformUser getPlatformUserfromJsonObject(JsonObject userObject) {
		PlatformUser platformUser = null;
		if (userObject == null) {
			return platformUser;
		}

		try {
			platformUser = new PlatformUser();
			platformUser.setPfId(userObject.getString("id"));
			platformUser.setPfName(userObject.getString("name"));

			// sex
			String gender = "0";
			if (userObject.has("gender")) {
				gender = userObject.getString("gender");
				if (!NormalUtil.isNull(gender)
						&& (gender.equalsIgnoreCase("male") || gender
								.indexOf("男") >= 0)) {
					gender = "1";
				} else {
					gender = "0";
				}
			}
			platformUser.setPfSex(gender);

			// pic
			String pic = null;
			if (userObject.has("picture")) {
				pic = userObject.getString("picture");
			}
			if (NormalUtil.isNull(pic)) {
				pic = "http://static.ak.fbcdn.net/pics/d_silhouette.gif";
			}
			platformUser.setPfTinyurl(pic);
			platformUser.setPfHeadurl(pic);
			platformUser.setPfMainurl(pic);

			// birthday
			if (userObject.has("birthday")) {
				String birthday = userObject.getString("birthday");
				if (!NormalUtil.isNull(birthday)) {
					platformUser.setPfBirthday(birthday);
				}
			}

			// locale
			if (userObject.has("locale")) {
				String locale = userObject.getString("locale");
				if (!NormalUtil.isNull(locale)) {
					platformUser.setPfCountry(locale);
				}
			}

			// email
			if (userObject.has("email")) {
				String email = userObject.getString("email");
				if (!NormalUtil.isNull(email)) {
					platformUser.setPfEmail(email);
				}
			}

		} catch (JsonException e) {
			// e.printStackTrace();
			return null;
		}
		return platformUser;

	}

	/**
	 * 和facebook建立通信连接
	 * 
	 * @param serverUrl
	 *            renren Restapi url，
	 * @return
	 */
	public void connectToPlatform(String accessToken) {
		graphFacebookClient = new DefaultFacebookClient(accessToken);
		restClient = new DefaultLegacyFacebookClient(accessToken);
		this.accessToken = accessToken;
	}

	/**
	 * 判断用户是不是某个公共主页的粉丝
	 * 
	 * @param uid
	 *            用户UID
	 * @param page_id
	 *            公共主页ID，不填写/0 默认为当前应用的公共主页
	 */
	public boolean page_isFans(Map<String, String> paramsMap) {
		String uid = paramsMap.get(Param.ParamName.UID.getName());
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		String page_id = paramsMap.get(Param.ParamName.PAGE_ID.getName());

		if (NormalUtil.isNull(page_id)) {
			return false;
		}

		String method = "/me/likes/" + page_id;
		if (!NormalUtil.isNull(uid)) {
			method = "/" + uid + "/likes/" + page_id;
		}

		String connectUrl = FACEBOOK_GRAPH_ENDPOINT_URL + method
				+ "?access_token=" + this.accessToken;
		String isfanObj = NormalUtil.getURLConnectionInfo(connectUrl);
		// System.err.println(isfanObj);
		if (isfanObj != null && isfanObj.indexOf(page_id) > 0) {
			return true;
		}
		return false;

	}

	/**
	 * 类似于发送分享uidList：当前玩家的ID
	 * 
	 * @param uidList
	 *            接收通知的用户ID
	 * @param notification
	 *            发送通知内容
	 *            参考：http://developers.facebook.com/docs/reference/rest/links
	 *            .post
	 */
	public void postMessage(HashMap<String, Object> paramsMap) {
		// do something

	}

	/**
	 * 发送新鲜事<br>
	 * 
	 * @param feedId
	 *            ：新鲜事Id<br>
	 * @param bodyArgs
	 *            ：新鲜事boby参数数组<br>
	 * @param resultMap
	 *            ：返回给flash的map<br>
	 *            参考http://wiki.dev.renren.com/wiki/%E8%87%AA%E5%AE%9A%E4%B9%89%E6
	 *            %96%B0%E9%B2%9C%E4%BA%8B
	 */
	public void postFeed(String feedId, String picName, String[] bodyArgs,
			String bodyIntelStr, HashMap resultMap, HashMap paramMap) {
		if (resultMap != null) {
			HashMap feedMap = new HashMap();
			feedMap.put("title", feedId);
			// feedMap.put("image", imageFileName);//暂时在js定义
			feedMap.put("args", bodyArgs);
			resultMap.put("XINXIANSHI", feedMap);
		}
	}

}
